package com.demo.webflux.redis;

import java.io.Serializable;
import java.nio.charset.Charset;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

	@Bean
	public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() {
		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
		redisStandaloneConfiguration.setDatabase(0);
		redisStandaloneConfiguration.setHostName("localhost");
		redisStandaloneConfiguration.setPort(6379);

		LettuceClientConfiguration.LettuceClientConfigurationBuilder builder = LettuceClientConfiguration.builder();
		return new LettuceConnectionFactory(redisStandaloneConfiguration, builder.build());
	}

	@Bean
	public ReactiveRedisTemplate<String, Serializable> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory){
		Jackson2JsonRedisSerializer<Serializable> serializer = new Jackson2JsonRedisSerializer<>(Serializable.class);
		RedisSerializationContext.RedisSerializationContextBuilder<String, Serializable> builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer(Charset.forName("utf-8")));
		RedisSerializationContext<String, Serializable> context = builder.value(serializer).build();

		return new ReactiveRedisTemplate<>(factory, context);
	}

}
